/**
 * Copyright (C) 2010 Sergey Grigoriev <s.a.grigoriev@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.gmf.core

import java.util.concurrent.atomic.AtomicBoolean

/**
 * Collects output from process streams
 */
class ProcessStreamReader {
  String stdOut
  String stdErr
  private final Process ps

  /**
   * @param ps Running process
   */
  ProcessStreamReader(ps) {
    this.ps = ps
  }

  def waitFor() {
    WatchingThread t1 = new WatchingThread(ps.in, 'watch stdout')
    WatchingThread t2 = new WatchingThread(ps.err, 'watch stderr')
    t1.start()
    t2.start()
    while (!(t1.completed.get() && t2.completed.get())) Thread.yield()
    stdOut = t1.result
    stdErr = t2.result
  }
}

class WatchingThread implements Runnable {
  final AtomicBoolean completed = new AtomicBoolean()
  InputStream is
  String result
  String name

  def WatchingThread(is, name) {
    this.is = is;
    this.name = name
  }

  Thread start() { new Thread(this, name).start() }

  @Override
  void run() {
    result = is.text
    completed.set true
  }
}
